import { defineComponent, watch, ref, computed, unref } from 'vue';
import { omit } from 'lodash-es';
import { Drawer } from 'ant-design-vue';
import type { HookDrawerProps } from './types';
import { isFunction } from '@/utils/is';

export type MyDrawerInstance = InstanceType<typeof MyDrawer>;

export const MyDrawer = defineComponent({
  props: ['content', 'closeDrawer', 'open', 'extra', 'defaultExtra'],
  setup(props, { attrs, expose }) {
    const confirmLoading = ref<boolean>(false);

    const propsRef = ref({ ...attrs, ...props });

    const getProps = computed(() => {
      return { ...attrs, ...props, ...unref(propsRef) };
    });

    const bindValues = computed(() => {
      const _props = unref(getProps);

      return {
        width: '50%',
        ...omit(_props, ['onClose', 'content', 'closeDrawer']),
        open: _props.open,
        onClose: handleCancel,
        footer: _props.extra ?? (_props.defaultExtra ? defaultExtraFunc() : null),
        footerStyle:
          _props.footerStyle ??
          (_props.defaultExtra
            ? {
                display: 'flex',
                flexDirection: 'row-reverse',
              }
            : null),
      };
    });

    const setVisible = (open: boolean) => {
      propsRef.value.open = open;
    };

    const setProps = (props: HookDrawerProps) => {
      propsRef.value = {
        ...unref(getProps),
        ...props,
      };
    };

    watch(
      () => propsRef.value.open,
      (val) => {
        Object.is(val, false) && props.closeDrawer?.();
      },
    );

    const handleConfirm = async (e: MouseEvent) => {
      confirmLoading.value = true;
      try {
        // @ts-ignore
        await unref(getProps)?.onOk?.(e);
        setVisible(false);
      } catch (error) {
        return Promise.reject(error);
      } finally {
        confirmLoading.value = false;
      }
    };
    const handleCancel = async (e: MouseEvent) => {
      // @ts-ignore
      await unref(getProps)?.onClose?.(e);
      setVisible(false);
    };
    const defaultExtraFunc = () => {
      return (
        <>
          <a-button
            class="ml-8px"
            loading={unref(confirmLoading)}
            onclick={handleConfirm}
            type="primary"
          >
            确定
          </a-button>
          <a-button onclick={handleCancel}>取消</a-button>
        </>
      );
    };

    expose({
      setProps,
    });

    return () => {
      const _props = unref(getProps);
      const { content } = _props;

      const Content = isFunction(content) ? content() : content;

      return <Drawer {...unref(bindValues)}>{Content}</Drawer>;
    };
  },
});
